// ArrayBuffer转16进度字符串示例
function buf2hex(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}


// 字符串转为ArrayBuffer对象，参数为字符串
function stringToHexBuffer(data) {
  //var data = 'AA5504B10000B5'
  var typedArray = new Uint8Array(data.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))
  return typedArray.buffer
}

function stringToArrayBuffer(str) {
    var bytes = new Array();
    var len, c;
    len = str.length;
    for (var i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if (c >= 0x010000 && c <= 0x10FFFF) {
            bytes.push(((c >> 18) & 0x07) | 0xF0);
            bytes.push(((c >> 12) & 0x3F) | 0x80);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if (c >= 0x000800 && c <= 0x00FFFF) {
            bytes.push(((c >> 12) & 0x0F) | 0xE0);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if (c >= 0x000080 && c <= 0x0007FF) {
            bytes.push(((c >> 6) & 0x1F) | 0xC0);
            bytes.push((c & 0x3F) | 0x80);
        } else {
            bytes.push(c & 0xFF);
        }
    }
    var array = new Int8Array(bytes.length);
    for (var i = 0; i <= bytes.length; i++) {
        array[i] = bytes[i];
    }
    return array.buffer;
    }


// 字符串转十六进制
function stringToHexStr(str) {
  var num = parseInt(str);
  var s = num.toString(16);       
  if(s.length == 1){
    s = "0" + s
  }
  return s;
}

// 字符串自动补0
function stringWithLength(str,length) {
  if(str.length > length){
    return;
  }
  var result = "";
  for(var i = 0; i < (length - str.length); i++){
    result = result + "0";
  }

  return result + str;
}

function arrBufToString(arrBuf){
    let unit8Arr = new Uint8Array(arrBuf) ;
    let encodedString = String.fromCharCode.apply(null, unit8Arr);
    return  decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
} 


module.exports = {
  buf2hex: buf2hex,
  stringToHexBuffer: stringToHexBuffer,
  stringWithLength: stringWithLength,
  stringToHexStr: stringToHexStr,
  arrBufToString: arrBufToString,
  stringToArrayBuffer: stringToArrayBuffer
}
